import { Component, OnInit } from '@angular/core';
import { YYListInfo } from 'src/model/yy/YYListInfo';
import { YY1API } from 'src/api/YY1API';
import { Router } from '@angular/router';
import { YYFilterListReq } from 'src/model/yy/YYFilterListReq';

@Component({
  selector: 'app-yy1-filter',
  templateUrl: './yy1-filter.page.html',
  styleUrls: ['./yy1-filter.page.scss'],
})
export class Yy1FilterPage implements OnInit {

  // 过滤条件
  queryText: string;
  // 每页记录数
  pageSize = 11;
  // 页码
  pageNum = 1;
  // 总记录数
  totalRecord = 1;
  // 页码集合
  pageNums: Array<number>;
  // 下拉框显示内容
  selectedText = '';
  // 列表
  list: Array<YYListInfo>;

  constructor(
    private yy1API: YY1API,
    private router: Router
  ) { }

  ngOnInit() {
    // 初始化
    // this.initPage();
  }

  // 查询
  async search(showLoader: boolean = true): Promise<Array<YYListInfo>> {
    // 条件
    let req = new YYFilterListReq();
    req.title = this.queryText;
    req.pageNum = this.pageNum;
    req.pageSize = this.pageSize;

    // 查询列表
    const ret = (await this.yy1API.filterList(req, showLoader));

    this.totalRecord = ret.totalRecord;
    this.pageNums = Array.from({ length: this.totalPageNum() }, (v, k) => k + 1);
    this.selectedText = this.pageNum + ' / ' + this.totalPageNum();

    return ret.lstInfo;
  }

  // 初始化
  async initPage() {
    // 查询
    this.list = await this.search();
  }

  // 刷新
  async doRefresh(event: any) {
    // 查询
    this.list = await this.search(false);

    // 刷新完成
    event.target.complete();
  }

  // 上一页
  toPrePage() {
    let curPageNum = Number(this.pageNum) - 1;
    if (curPageNum <= 0) {
      curPageNum = 1;
    }

    if (curPageNum !== this.pageNum) {
      this.pageNum = curPageNum;
    }
  }

  // 下一页
  toNextPage() {
    let curPageNum = Number(this.pageNum) + 1;
    if (curPageNum >= this.totalPageNum()) {
      curPageNum = this.totalPageNum();
    }

    if (curPageNum !== this.pageNum) {
      this.pageNum = curPageNum;
    }
  }

  // 页码改变
  pageChanged() {
    this.initPage();
  }

  // 总页数
  totalPageNum(): number {
    const totalPageNum = Math.ceil(this.totalRecord / this.pageSize);
    return totalPageNum;
  }

  // 跳转详情页面
  async openDetail(item: YYListInfo) {
    this.router.navigate(
      ['tabs/yy1Tab/yy1Detail'],
      { queryParams: { id: item.id } });
  }
}
